from fetchemApp.models import *
import datetime
import smtplib
import time

from django.db import transaction

@transaction.commit_manually
def flush_transaction():
    """
    Flush the current transaction so we don't read stale data

    Use in long running processes to make sure fresh data is read from
    the database.  This is a problem with MySQL and the default
    transaction mode.  You can fix it by setting
    "transaction-isolation = READ-COMMITTED" in my.cnf or by calling
    this function at the appropriate moment
    """
    transaction.commit()

def update():
    ##########
    flush_transaction()
    invalidcourse = []
    now = datetime.datetime.now()
    try:
        smtpserver = smtplib.SMTP("smtp.gmail.com",587)
    except:
        invalidcourse.append('Connection Unavailable')
        return invalidcourse
    
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
#    time = now+datetime.timedelta(0,41400)
    ##########
    print now
    if now.month <=6:
        sem = 'Winter'
    else:
        sem = 'Monsoon'
    courses = Course.objects.filter(Year=now.year,Semester=sem)
    for c in courses:
        ##########
        Frm = c.SubEmail
        Pss = c.SubPassword
        try:
            smtpserver.login(Frm,Pss)
        except smtplib.SMTPAuthenticationError:
            print 'INVALID'
            invalidcourse.append(c)
            continue
        ##########
        x = c.assignment_set.all()
        y = c.Students.all()
        stulist = []
        for t in y:
            stulist.append(t.Email)
        print "Stulist...", stulist
        for a in x:
            print "IN..."
            print "If...", a.StartDateTime<now and a.EndDateTime>now
            if a.StartDateTime<now and a.EndDateTime + datetime.timedelta(0, 900)>now:
                sublist = []
                subs =  a.submission_set.all()
                print "S...", subs
                for s in subs:
                    sublist.append(s.student.Email)
                for temp in stulist:
                    K = Student.objects.filter(Email=temp)[0]
                    print "Email...", temp
                    print "Student...", K.Name
                    if temp not in sublist:
                        print "Checking time..."
                        if a.EndDateTime-datetime.timedelta(0,(7200+600))<now and a.EndDateTime-datetime.timedelta(0,(7200-600))>now :
                            print "Time to notify..."
                            ##########
                            to = str(K.Email)
                            body = 'The -'+str(a)+'- has not yet been received from your account!'
                            Subj =  str(c.CourseNo)+' '+str(a.SubjectLine)+ '- Not Received'
                            header = 'To:' + to + '\n' + 'From: ' + Frm + '\n' + 'Subject:' + Subj + '\n'
                            msg = header + '\n' + body + '\n Thank you'
                            print "Mailing..."
                            smtpserver.sendmail(Frm, to, msg)
                            ##########
                    else:
                        studsub = a.submission_set.filter(student=Student.objects.filter(Email=temp)[0])[0]
                        if studsub.Status=='Received' or studsub.Status=='Graded' or studsub.Status=='Marked':
                            to = str(K.Email)
                            body = 'The -'+str(a)+'- has been received!'
                            Subj = str(c.CourseNo)+' '+str(a.SubjectLine)+ '- Received'
                            header = 'To:' + to + '\n' + 'From: ' + Frm + '\n' + 'Subject:' + Subj + '\n'
                            msg = header + '\n' + body + '\n Thank you'
                            smtpserver.sendmail(Frm, to, msg)
                            
                            if(studsub.Status=='Received'):
                                studsub.Status='Accepted'
                            studsub.save()
    ##########
    smtpserver.close()
    ##########
    #threading.Timer(900, update).start()
    #print invalidcourse
    return invalidcourse
    
def theNotifyLooper():
    while(True):
        update()
        #Possibly do something about the courses with wrong credentials.
        print 'Going to sleep!'
        time.sleep(900)
